import React, { useEffect, useState, useContext } from 'react';
import { connect } from 'umi';
import { Button, Form, Row, Col, Spin, message } from 'antd';
import { history } from 'umi'
import classNames from 'classnames';

import { BottomAction } from '@/components';
import { SearchInput } from '@/components/UserForm';

import { TabMenuRouter, TabContextMenuFilter } from '@/pages/SalaryManage/components/MenuFilterRouter';
import { TabStoreContext } from '@/pages/SalaryManage/constant/TabStoreContext';

import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { withRoutePage } from '@/utils/enhanceUtils';
import { isSuccess } from '@/utils/request';
import AuthComponent from '@/utils/auth/AuthComponent';
import eventBus from '@/utils/eventBus';
import OrganizationSelect from '@/components/OrganizationSelect';

import { queryBaseSettingInfo, onSaveBaseSetting, queryDictList } from '@/services/salaryManage/salaryCalculate';
import { queryEmployeeList } from '@/services/salaryManage/salaryCommon';

import DictSelect from '@/pages/SalaryManage/SalaryCalculate/ParameterSetting/components/DictSelect';
import { fetchOrganizationListAndDefault } from '@/pages/SalaryManage/utils';
import salaryStyle from '@/pages/SalaryManage/salaryManage.less';
import styles from '../style.less';

/** 【参数设置】权限码 */
const SALARY_SETTING_AUTH_CODE = 'finance:setting:basic:param';

const MENU_AUTH_CODE_MAP = {
    CN: [SALARY_SETTING_AUTH_CODE],
    SG: [SALARY_SETTING_AUTH_CODE]
};

const formItemLayout = {
    labelCol: {
        md: { span: 9 },
        xs: { span: 24 },
        sm: { span: 24 }
    },
    wrapperCol: {
        md: { span: 15 },
        xs: { span: 24 },
        sm: { span: 24 }
    }
};

const BaseSetting = ({ form, dispatch }) => {
    const [editData, setEditData] = useState({});
    const [dictList, setDictList] = useState([]);
    const { getFieldDecorator, validateFields, resetFields } = form;
    const {
        store: { selectOrganizationCode: selOrgCode },
        mergeTabStore
    } = useContext(TabStoreContext);
    const [loading, setLoading] = useState(false);
    const [organizationTreeData, setOrganizationTreeData] = useState([]);
    const [selectOrganizationCode, setSelectOrganizationCode] = useState(null);

    useEffect(() => {
        if (selOrgCode && selOrgCode !== selectOrganizationCode) {
            setSelectOrganizationCode(selOrgCode);
        }
    }, [selOrgCode]);

    const getDictList = async () => {
        try {
            const { code, data = {} } = await queryDictList('ScaleOptions,RoundingModeOptions');
            if (code === 10000) {
                setDictList(data);
            }
        } catch (e) {
            console.log(e);
        }
    };
    const initData = async orgCode => {
        setLoading(true);
        try {
            const { code, data = {} } = await queryBaseSettingInfo(orgCode);
            if (code === 10000) {
                setEditData(data);
            } else {
                setEditData({});
            }
            setLoading(false);
        } catch (e) {
            console.log(e);
            setLoading(false);
        }
    };
    const onSave = async values => {
        console.log(values, editData);
        try {
            setLoading(true);
            const { code, msg } = await onSaveBaseSetting({
                paramMap: {
                    ...values
                },
                organizationCode: selectOrganizationCode
            });
            if (code === 10000) {
                message.success('保存成功！');
                if (Number(values.scale) !== Number(editData.scale)) {
                    dispatch({ type: 'finance/fetchBaseSetting' });
                    eventBus.emit('finance.baseSetting', selectOrganizationCode);
                }
            } else {
                message.error(msg);
            }
            setLoading(false);
        } catch (e) {
            console.log(e);
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchOrganizationListAndDefault().then(
            ({ organizationResponse, defaultOrganizationCode: defaultSelectCode }) => {
                setOrganizationTreeData(organizationResponse);
                setSelectOrganizationCode(defaultSelectCode);
            }
        );
    }, []);

    useEffect(() => {
        getDictList();
    }, []);

    useEffect(() => {
        if (selectOrganizationCode) {
            mergeTabStore({
                selectOrganizationCode,
                countryNameCode: null
            });
            resetFields();
            initData(selectOrganizationCode);
        }
    }, [selectOrganizationCode]);

    return (
        <PageHeaderWrapper type="success">
            <TabContextMenuFilter>
                <TabMenuRouter
                    authCodeMap={MENU_AUTH_CODE_MAP}
                    type="baseSetting"
                    extraButton={
                        <div className={salaryStyle.flex}>
                            <div className={classNames([salaryStyle.flex, salaryStyle.mr12])}>
                                <OrganizationSelect
                                    isStrictly
                                    isNeedPermission
                                    style={{ width: 220 }}
                                    treeDataFromProp
                                    treeDataList={organizationTreeData}
                                    allowClear={false}
                                    value={selectOrganizationCode}
                                    dropdownMatchSelectWidth
                                    onChange={orgCode => setSelectOrganizationCode(orgCode)}
                                />
                            </div>
                            <div>
                                <Button
                                    onClick={() =>
                                        history.push({
                                            pathname: '/finance/setting/baseSetting/parameterSettingLog',
                                            query: {
                                                organizationCode: selectOrganizationCode
                                            },
                                            state: {
                                                tabRoute: true,
                                                tabRefresh: true
                                            }
                                        })
                                    }
                                >
                                    操作日志
                                </Button>
                            </div>
                        </div>
                    }
                >
                    <div className={styles.container}>
                        <Spin spinning={loading}>
                            <div className={styles.container}>
                                <div
                                    className={styles.salaryContent}
                                    style={{ paddingTop: '30px', paddingBottom: '300px', borderBottom: 'none' }}
                                >
                                    <Form {...formItemLayout} hideRequiredMark name="base-setting">
                                        <Row gutter={24}>
                                            <div className={styles.parameterTitle}>小数位逻辑</div>
                                        </Row>
                                        <Row gutter={24}>
                                            <Col span={8}>
                                                <Form.Item label="小数保留逻辑">
                                                    {getFieldDecorator('roundingMode', {
                                                        initialValue: editData.roundingMode
                                                            ? // eslint-disable-next-line no-bitwise
                                                              ~~editData.roundingMode
                                                            : undefined,
                                                        rules: [
                                                            {
                                                                required: true,
                                                                message: '请选择小数保留逻辑'
                                                            }
                                                        ]
                                                    })(
                                                        <DictSelect
                                                            dictList={dictList}
                                                            dictName="RoundingModeOptions"
                                                        />
                                                    )}
                                                </Form.Item>
                                            </Col>
                                            <Col span={8}>
                                                <Form.Item label="有效保留小数">
                                                    {getFieldDecorator('scale', {
                                                        initialValue: editData.scale
                                                            ? // eslint-disable-next-line no-bitwise
                                                              ~~editData.scale
                                                            : undefined,
                                                        rules: [
                                                            {
                                                                required: true,
                                                                message: '请选择有效保留小数'
                                                            }
                                                        ]
                                                    })(<DictSelect dictList={dictList} dictName="ScaleOptions" />)}
                                                </Form.Item>
                                            </Col>
                                        </Row>
                                        <Row gutter={24}>
                                            <Col span={8}>
                                                <Form.Item label="兜底人">
                                                    {getFieldDecorator('bottomManEmployeeCode', {
                                                        initialValue: editData.bottomManEmployeeCode || undefined
                                                    })(
                                                        <SearchInput
                                                            params={{
                                                                organizationCode: selectOrganizationCode
                                                            }}
                                                            getData={async params => {
                                                                if (!params.organizationCode) {
                                                                    return [];
                                                                }
                                                                const employeeResponse = await queryEmployeeList({
                                                                    organizationCode: params.organizationCode
                                                                });
                                                                return isSuccess(employeeResponse)
                                                                    ? employeeResponse.data || []
                                                                    : [];
                                                            }}
                                                            selectProps={{
                                                                placeholder: '请输入员工姓名',
                                                                allowClear: true
                                                            }}
                                                            fieldsName={{
                                                                value: 'employeeCode',
                                                                title: 'name'
                                                            }}
                                                        />
                                                    )}
                                                </Form.Item>
                                            </Col>
                                        </Row>
                                    </Form>
                                </div>
                                <AuthComponent code="finance:setting:basic:param:save">
                                    <BottomAction>
                                        <Button
                                            type="primary"
                                            onClick={() => {
                                                validateFields((err, values) => {
                                                    console.log(values);
                                                    if (!err) {
                                                        console.log('Received values of form: ', values);
                                                        onSave(values);
                                                    }
                                                });
                                            }}
                                        >
                                            保存
                                        </Button>
                                    </BottomAction>
                                </AuthComponent>
                            </div>
                        </Spin>
                    </div>
                </TabMenuRouter>
            </TabContextMenuFilter>
        </PageHeaderWrapper>
    );
};
export default withRoutePage(connect(() => ({}))(Form.create({ name: 'base-setting' })(BaseSetting)));
